package com.reggie.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.reggie.dto.DishDto;
import com.reggie.entity.Dish;
import com.reggie.entity.DishFlavor;
import com.reggie.mapper.DishMapper;
import com.reggie.service.DishFlavorService;
import com.reggie.service.DishService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 78664
 * @description 针对表【dish(菜品管理)】的数据库操作Service实现
 * @createDate 2022-09-01 18:03:26
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish>
        implements DishService {

    @Resource
    private DishFlavorService dishFlavorService;

    /**
     * 新增菜品，同时插入对应的口味数据，需要操作两张表dish dish_Flavor
     *
     * @param dishDto 菜品数据
     */

    @Override
    @Transactional
    public void saveWithFlavors(DishDto dishDto) {
        // 保存菜品
        this.save(dishDto);
        Long dishId = dishDto.getId();
        dishDto.getFlavors().forEach(dishFlavor -> {
            dishFlavor.setDishId(dishId);
        });
        // 保存口味
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }

    /**
     * 根据菜品id查询菜品与菜品口味
     *
     * @param id 菜品id
     * @return 菜品信息
     */
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        DishDto dishDto = new DishDto();
        // 查询菜品
        Dish dish = this.getById(id);
        BeanUtil.copyProperties(dish, dishDto);
        // 查询口味
        LambdaQueryWrapper<DishFlavor> queryWrapper = Wrappers.lambdaQuery(DishFlavor.class);
        queryWrapper.eq(DishFlavor::getDishId, dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    /**
     * 修改菜品
     *
     * @param dishDto 修改数据
     */
    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
        // 更新dish
        this.updateById(dishDto);
        // 更新dishFlavor【先删后增】
        LambdaQueryWrapper<DishFlavor> queryWrapper = Wrappers.lambdaQuery(DishFlavor.class);
        queryWrapper.eq(DishFlavor::getDishId, dishDto.getId());
        dishFlavorService.remove(queryWrapper);
        dishDto.getFlavors().forEach(dishFlavor -> {
            dishFlavor.setDishId(dishDto.getId());
        });
        dishFlavorService.saveBatch(dishDto.getFlavors());
    }
}




